# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import datetime,logging,os.path,sqlite3
from .conflibs import confgetval

logger = logging.getLogger()



ListReplicateDb = []
def addreplicdb(ldb=None):
    listdbs = confgetval('pimucha.conf','SqliteDB','ReplicateDb','')
    for db in listdbs.split(','):
        if os.path.isfile(db):
            ListReplicateDb.append(db)
    logger.debug('ListReplicateDb %s', repr(ListReplicateDb))
    return


def dumprows(rows):
    msg = []
    for row in rows:
        ln = []
        for r in row:
            ln.append(repr(r))                
        msg.append('|'.join(ln))
    return msg


def initdbconn():
    DefaultDB3 = confgetval('pimucha.conf','SqliteDB','ConfigDB','dbase.db3')
    conn = sqlite3.connect(DefaultDB3, check_same_thread=False)
    conn.text_factory = str
    return conn
DefaultCONN = initdbconn()


def majdb3(req,data):
    conn = DefaultCONN
    #cur = conn.cursor()
    nb = conn.execute(req,data).rowcount
    conn.commit()
    for db in ListReplicateDb:
        try:
            conn1 = sqlite3.connect(db)
            conn1.execute(req,data)
            conn1.commit()
            conn1.close()
        except:
            pass
    return nb


def ralldb3(req,data):
    conn = DefaultCONN
    cur = conn.cursor()
    cur.execute(req,data)
    rows = cur.fetchall()
    return rows


def reqdb3(req,data):
    conn = DefaultCONN
    cur = conn.cursor()
    cur.execute(req,data)
    row = cur.fetchone()
    return row


def fieldsdb3(tablename):
    req = 'SELECT * FROM ' + tablename + ';'
    conn = DefaultCONN
    cur = conn.cursor()
    cur.execute(req,[])
    f = []
    for r in cur.description:
        f.append(r[0])
    return f


FctDb2Dict = {
    'UNITS':["SELECT unitId,enabled,unit FROM unitIds ","(rows[i][0],list(rows[i][0:]))"],
    'UNITIDS':["SELECT iddecoder,unitId,unit FROM unitIds ","((rows[i][0],rows[i][1]),rows[i][2])"],
    'PARAMETERS':["SELECT parameter,modaddrId,unit,enabled FROM parameterIds ","(rows[i][0:2],rows[i][0:])"],
    }


def db2dict(cnxfct,condition=None):
    logger.debug("Request Sqlite for %s",cnxfct)
    if condition :
        req = FctDb2Dict[cnxfct][0] + condition
    else:
        req = FctDb2Dict[cnxfct][0]
    pair = FctDb2Dict[cnxfct][1]
    rows = ralldb3(req,'')
    a =[]
    for i in range(0,len(rows)):
         a.append(eval(pair))
    return dict(a)


def lsdict(dictobj):
    a = []
    for k in dictobj:
        a.append((repr(k) + ':' + repr(dictobj[k])))
    return '\n'.join(a)
